package com.mm.fam.web.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.mm.fam.common.utils.LoggerUtils;
import com.mm.fam.web.base.*;
import com.mm.fam.web.entity.SysPermission;
import com.mm.fam.web.entity.ins.PermissionTreeIns;
import com.mm.fam.web.service.SysPermissionService;
import com.mm.fam.web.vo.MenuPermissionTree;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

/**
 * 权限资源文件管理
 */
@Api(value="授权模块", description="授权模块")
@RestController
@RequestMapping(value = "/api/permission")
public class SysPermissionController {

    @Autowired
    private SysPermissionService sysPermissionService;

    @GetMapping("/queryMenuPermissionList")
    @ApiOperation(value="分页查询所有子集菜单", notes="分页查询所有子集菜单")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType="query", required=false, name = "pageNo", value = "页码", dataType = "Integer"),
            @ApiImplicitParam(paramType="query", required=false, name = "pageSize", value = "页数", dataType = "Integer"),
            @ApiImplicitParam(paramType="query", required=false, name = "search", value = "搜索内容", dataType = "String"),
    })
    public ResponseEntity<ResponseModel<IPage<MenuPermissionTree>>> queryMenuPermissionList(
            @RequestParam(value = "pageNo", defaultValue = "1") int pageNo,
            @RequestParam(value = "pageSize", defaultValue = "10") int pageSize,
            @RequestParam(value = "search", defaultValue = "") String search){
        ResponseEntity<ResponseModel<IPage<MenuPermissionTree>>> re = null;
        try{
            re = sysPermissionService.queryMenuPermissionList(pageNo, pageSize, search);
        }catch(Exception e){
            LoggerUtils.error(getClass(),"[SysPermissionController queryMenuPermissionList]" + e.getMessage());
            re = ResponseUtil.error(CommonConstant.Message.OPTION_FAILURE);
        }
        return re;
    }

    @PostMapping("/saveOrUpdate")
    @ApiOperation(value="新增或修改可访问权限", notes="新增或修改可访问权限")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType="body", required=false, name = "permission", value = "可访问资源对象", dataType = "SysPermission"),
    })
    public ResponseEntity<ResponseModel<Object>> saveOrUpdate(@RequestBody SysPermission permission) {
        ResponseEntity<ResponseModel<Object>> re = null;
        try {
            re = sysPermissionService.savePermission(permission);
        } catch (Exception e) {
            LoggerUtils.error(getClass(), "[SysPermissionController saveOrUpdate ]" + e.getMessage());
            re = ResponseUtil.error(CommonConstant.Message.OPTION_FAILURE);
        }
        return re;
    }

    // 删除
    @Deprecated
    @PostMapping("/deleteBatch")
    public ResponseEntitySelf<String> deleteBatch(@RequestBody Map<String, Object> param) {
        ResponseEntitySelf<String> res = new ResponseEntitySelf<>();
        List<String> ids = (List<String>) param.get("ids");
        try {
            String msg = sysPermissionService.deleteBatch(ids);
            res.success(msg);
        } catch (Exception e) {
            LoggerUtils.error(getClass(), "删除权限资源:" + e.getMessage());
            res.failure("该权限可能存在数据关联,暂时无法删除");
        }
        return res;
    }

    /**
     * 指定资源权限树
     *
     * @param parentId
     * @return
     */
    @Deprecated
    @GetMapping("/page")
    public ResponsePage<PermissionTreeIns> getPermissionTree(@RequestParam(value = "name", defaultValue = "") String name,
                                                             @RequestParam(value = "current", defaultValue = "") int current,
                                                             @RequestParam(value = "pageSize", defaultValue = "10") int pageSize,
                                                             @RequestParam(value = "parentId", defaultValue = "0") String parentId) {
        ResponsePage<PermissionTreeIns> res = new ResponsePage<PermissionTreeIns>();
        try {
            IPage<PermissionTreeIns> page = sysPermissionService.getPermissionTree(current, pageSize, parentId, name);
            List<PermissionTreeIns> permissionTree = page.getRecords();
            setTree(permissionTree);
            res.setPage(page);
        } catch (Exception e) {
            LoggerUtils.error(getClass(), "获取权限树失败:" + e.getMessage());
            res.failure(CommonConstant.Message.OPTION_FAILURE);
        }
        return res;
    }


    /**
     * 指定资源权限树
     *
     * @param parentId
     * @return
     */
    @Deprecated
    @GetMapping("/getPermissionByParentId")
    public ResponseList<PermissionTreeIns> getPermissionTree(@RequestParam(value = "parentId", defaultValue = "0") Integer parentId) {
        ResponseList<PermissionTreeIns> res = new ResponseList<PermissionTreeIns>();
        try {

            List<PermissionTreeIns> permissionTree = sysPermissionService.getPermissionTree(parentId);
            res.setData(permissionTree);
        } catch (Exception e) {
            e.printStackTrace();
            LoggerUtils.error(getClass(), "获取权限树失败:" + e.getMessage());
            res.failure(CommonConstant.Message.OPTION_FAILURE);
        }
        return res;
    }


    /**
     * 设置权限树 状态(设置 是否选中)
     *
     * @param trees 菜单树
     * @param trees 具有权限的菜单
     */
    private boolean setTree(List<PermissionTreeIns> trees) {
        if (trees == null || trees.isEmpty())
            return false;
        boolean flag = false;
        for (PermissionTreeIns tree : trees) {
            if (tree.getChildren() != null && !tree.getChildren().isEmpty()) {
                tree.setIsParent(true);
                if (setTree(tree.getChildren())) {
                    tree.setChecked(true);
                }
            }
        }
        return flag;
    }

}
